package com.backend.modules.task.repository;

import com.backend.modules.task.entity.Task;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.data.repository.query.Param;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 任务数据访问接口
 */
@Repository
public interface TaskRepository extends JpaRepository<Task, Long>, JpaSpecificationExecutor<Task> {
    
    /**
     * 根据班级ID查询任务
     */
    @Query("SELECT t FROM Task t WHERE t.classId = :classId")
    List<Task> findByClassId(@Param("classId") Long classId);
    
    /**
     * 查询活跃任务
     */
    @Query("SELECT t FROM Task t " +
        "WHERE (:gradeId IS NULL OR t.classInfo.parent.parent.id = :gradeId) " +
        "AND (:majorId IS NULL OR t.classInfo.parent.id = :majorId) " +
        "AND (:classId IS NULL OR t.classInfo.id = :classId) " +
        "AND t.deadline > CURRENT_TIMESTAMP")
    List<Task> findActiveTasksByConditions(
        @Param("gradeId") Long gradeId,
        @Param("majorId") Long majorId,
        @Param("classId") Long classId);

    /**
     * 查询指定时间范围内截止的任务
     */
    List<Task> findByDeadlineBetween(LocalDateTime start, LocalDateTime end);

    @Query("SELECT COUNT(t) FROM Task t WHERE t.deleted = false")
    Integer countAll();
    
    @Query("SELECT COUNT(t) FROM Task t WHERE t.deleted = false AND t.deadline > CURRENT_TIMESTAMP")
    Integer countOngoing();
} 